package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.BaseContext;
import com.common.CustomException;
import com.entity.*;
import com.mapper.OrdersMapper;
import com.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取操作者的id
        Long currentId = BaseContext.getCurrentId();
        //通过id获取操作者的购物车
        LambdaQueryWrapper<ShoppingCart> lqw1=new LambdaQueryWrapper<>();
        lqw1.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw1);
        if (shoppingCartList==null||shoppingCartList.size()==0){
            throw new CustomException("购物车为空，流汗.jpg");
        }
        //获取用户信息
        LambdaQueryWrapper<User> lqw2=new LambdaQueryWrapper<>();
        lqw2.eq(User::getId,currentId);
        User user = userService.getOne(lqw2);
        //获取用户地址信息
        LambdaQueryWrapper<AddressBook> lqw3=new LambdaQueryWrapper<>();
        Long addressBookId = orders.getAddressBookId();
        lqw3.eq(AddressBook::getId,addressBookId);
        AddressBook addressBook = addressBookService.getOne(lqw3);
        if (addressBook==null){
            throw new CustomException("查不到默认地址(流汗)");
        }
        //随机生成一个id
        long id = IdWorker.getId();
        //计算金额
        AtomicInteger amount=new AtomicInteger(0);//设置一个变量再遍历时记录总金额，该类型防止多并发出错
        List<OrderDetail> orderDetails=new ArrayList<>();
        //遍历购物车计算金额
        for (ShoppingCart shoppingCart:shoppingCartList){
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetails.add(orderDetail);
        }
        //提交订单信息
        orders.setId(id);//设置id
        orders.setNumber(String.valueOf(id));
        orders.setStatus(1);//设置订单状态
        orders.setUserId(currentId);//设置用户id
        orders.setAddressBookId(addressBookId);//设置地址id
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(2);
        orders.setAmount(new BigDecimal(amount.get()));//获取之前的amount并转化类型
        orders.setRemark(orders.getRemark());//设置备注
        orders.setUserName(user.getName());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        this.save(orders);
        //提交订单明细（多条）
        orderDetailService.saveBatch(orderDetails);
        //清空该用户的购物车
        LambdaQueryWrapper<ShoppingCart> lqw4=new LambdaQueryWrapper<>();
        lqw4.eq(ShoppingCart::getUserId,currentId);
        shoppingCartService.remove(lqw4);
    }
}
